package com.orchard.orchardfarmmanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orchard.orchardfarmmanagementsystem.dto.MaintenanceRecordsDTO;
import com.orchard.orchardfarmmanagementsystem.dto.MaterialDTO;
import com.orchard.orchardfarmmanagementsystem.dto.SuppliesDTO;
import com.orchard.orchardfarmmanagementsystem.entity.Inventory;
import com.orchard.orchardfarmmanagementsystem.entity.MaintenanceRecords;
import com.orchard.orchardfarmmanagementsystem.entity.Materials;
import com.orchard.orchardfarmmanagementsystem.mapper.InventoryMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.MaintenanceMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.MaintenanceRecordsMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.SuppliesMapper;
import com.orchard.orchardfarmmanagementsystem.service.MaintenanceService;
import com.orchard.orchardfarmmanagementsystem.service.SuppliesService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import com.orchard.orchardfarmmanagementsystem.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MaintenanceServiceImpl extends ServiceImpl<MaintenanceMapper, MaintenanceRecords> implements MaintenanceService {

    @Autowired
    private SuppliesMapper suppliesMapper;

    @Autowired
    private MaintenanceRecordsMapper maintenanceRecordsMapper;

    @Autowired
    private InventoryMapper inventoryMapper;


    @Override
    public List<MaintenanceRecordsDTO> getMaintenanceRecords(Integer materialId) {
        // 查询所有与指定物资相关的维护记录
        List<MaintenanceRecords> records = maintenanceRecordsMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MaintenanceRecords>()
                        .eq("material_id", materialId)
        );

        // 定义日期格式化器

        // 将实体类转换为 DTO 列表，并格式化日期字段
        List<MaintenanceRecordsDTO> recordDTOs = records.stream()
                .map(record -> {
                    MaintenanceRecordsDTO dto = new MaintenanceRecordsDTO();
                    BeanUtils.copyProperties(record, dto);

                    return dto;
                })
                .collect(Collectors.toList());

        return recordDTOs;
    }

    @Override
    @Transactional
    public MaintenanceRecordsDTO createMaintenanceRecords(MaintenanceRecordsDTO maintenanceRecordsDTO) {
        //新增维修的记录，同时扣减库存，同时判断库存是否充足
        // 检查库存是否足够
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_id", maintenanceRecordsDTO.getMaterialId());
        Inventory inventory = inventoryMapper.selectOne(queryWrapper);
        if (inventory == null || inventory.getCurrentQuantity() < maintenanceRecordsDTO.getQuantity()) {
            throw new RuntimeException("库存不足,无法扣减维护信息");
        }

        // 扣减库存
        inventory.setCurrentQuantity(inventory.getCurrentQuantity() - maintenanceRecordsDTO.getQuantity());
        inventoryMapper.updateById(inventory);

        // 创建新的维护记录实体对象
        MaintenanceRecords newRecord = new MaintenanceRecords();
        BeanUtils.copyProperties(maintenanceRecordsDTO, newRecord);
        newRecord.setPerformedBy(UserHolder.getUser().getUsername());

        // 使用 MyBatis-Plus 的 insert 方法保存新的维护记录到数据库
        boolean saved = maintenanceRecordsMapper.insert(newRecord) > 0;
        if (!saved) {
            throw new RuntimeException("创建维护信息失败");
        }

        // 将新保存的维护记录转换为 DTO 并返回
        MaintenanceRecordsDTO resultDTO = new MaintenanceRecordsDTO();
        BeanUtils.copyProperties(newRecord, resultDTO);

        return resultDTO;
    }

    @Override
    public List<MaintenanceRecordsDTO> getAllMaintenanceRecords() {
        List<MaintenanceRecords> records = maintenanceRecordsMapper.selectList(null); // 不带条件查询所有记录

        return records.stream()
                .map(record -> {
                    MaintenanceRecordsDTO dto = new MaintenanceRecordsDTO();
                    BeanUtils.copyProperties(record, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public MaintenanceRecordsDTO completeMaintenanceRecord(Integer id, MaintenanceRecordsDTO maintenanceRecordsDTO) {
        MaintenanceRecords record = maintenanceRecordsMapper.selectById(id);
        if (record == null) {
            throw new RuntimeException("维修记录不存在");
        }

        try {
            // 更新维修记录的状态和其他字段
            maintenanceRecordsDTO.setStatus("已完成"); // 或者根据业务逻辑设置其他状态
            BeanUtils.copyProperties(maintenanceRecordsDTO, record);

            // 更新数据库中的维修记录
            maintenanceRecordsMapper.updateById(record);

            // 更新库存（假设有一个方法可以根据维修记录更新库存）
            returnInventoryAfterMaintenance(record);

            // 回填更新后的信息到DTO中
            BeanUtils.copyProperties(record, maintenanceRecordsDTO);
        } catch (Exception e) {
            // 捕获异常并抛出，确保事务会回滚
            throw new RuntimeException("完成维修记录时发生错误：" + e.getMessage(), e);
        }

        return maintenanceRecordsDTO;
    }
    public void returnInventoryAfterMaintenance(MaintenanceRecords record) {
        // 根据维修记录中的物资ID和数量更新库存
        Integer materialId = record.getMaterialId();
        Integer quantity = record.getQuantity();

        // 获取当前库存
        Inventory inventory = inventoryMapper.selectById(materialId);
        if (inventory == null) {
            throw new RuntimeException("物资库存记录不存在");
        }

        // 更新库存数量
        inventory.setCurrentQuantity(inventory.getCurrentQuantity() + quantity);

        // 更新数据库中的库存信息
        inventoryMapper.updateById(inventory);
    }


    @Override
    @Transactional
    public Result deleteMaintenanceRecord(Integer id) {
        MaintenanceRecords record = maintenanceRecordsMapper.selectById(id);
        if (record == null) {
            return Result.error(50001,"维修记录不存在");
        }

        if (!"已完成".equals(record.getStatus())) {
            return Result.error(50001,"维修记录不存在");
        }

        int delete = maintenanceRecordsMapper.deleteById(id);
        if(delete <= 0){
            return Result.error(50001,"删除记录失败");
        }else{
            return Result.success("删除维修记录成功");
        }


    }

}


